package com.honglang.common.tools;

import java.util.ArrayList;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.htmlparser.jericho.Segment;
import net.htmlparser.jericho.Source;
@SuppressWarnings("unused")
public class HtmlCodeProcess {
   private final String codeTagPrefix ="[code]";
   private final String codeTagSufix = "[/code]";   
   private final String codePrefix = "&lt;pre";
   private final String codeSufix = "&gt;pre";
   private final String googlePrettyPrintPrefix = "<pre class='prettyprint'>";
   private final String googlePrettyPrintLineNumsPrefix = "<pre class='prettyprint linenums'>";
   private final String googlePrettyPrintSufix ="</pre>";
   private final String highlightPrintPrefix = "<pre><code>";
   private final String highlightPrintSufix = "</code></pre>";
   
   public String codeProcess(String html){
	      int words=0;
		  int criticalIndex=0;
		  Pattern p= Pattern.compile("<[^/]+?>([^<>]+?)</.+?>",Pattern.DOTALL);
		  Matcher m=p.matcher(html);
		  while(m.find()){
			  System.out.println(m.group(1));
			   if(m.group(1).length()+words>Constants.Words){	 
			     criticalIndex=m.start(1)+Constants.Words-words;
			     words=m.group(1).length()+words;
			     break;
			   }
			   else{
				   words=m.group(1).length()+words;
			   }
		  }
		  if(words<=Constants.Words){
			  criticalIndex=html.length();
		  }
	      ArrayList<String> list=new ArrayList<String>();
	      m.usePattern(Pattern.compile("[.]*(<.+?>)[.]*",Pattern.DOTALL));
		  m.region(0, criticalIndex);
		  String str;
		  while(m.find()){
			   str=m.group(1);
			   if(str.indexOf("/>")==-1){
			      if(str.indexOf("</")==-1){
			    	     list.add(str.substring(1,str.indexOf(" ")>0?str.indexOf(" "):str.indexOf(">"))); 
			      }
			      else{
			    	  list.remove(list.size()-1);
			      }
			   }
		  }
		  StringBuffer tempStr=new StringBuffer();
		  tempStr.append(html.substring(0, criticalIndex));
		  for(int i=list.size()-1;i>=0;i--){
			  tempStr.append("</"+list.get(i)+">");
		  }
		  return tempStr.toString();
		
   }
   
   public static String clearHtmlTag(String html){
		return new Segment(new Source(html.subSequence(0, html.length())),0,html.length()).getTextExtractor().toString();
   }
   
   public String saveCodeFragment(String html){
	   return html.replace(this.codeTagPrefix,this.highlightPrintPrefix).replace(this.codeTagSufix, this.highlightPrintSufix);
	   
   }
   
   public static void main(String[] args){
	   HtmlCodeProcess hp = new HtmlCodeProcess();
	   String html ="<div style='margin-bottom:4em'> hide</div><p>巍峨</p>" ;
	   System.out.println(hp.codeProcess(html));
	   System.out.println(HtmlCodeProcess.clearHtmlTag(html));
	   System.out.println(hp.saveCodeFragment("[code]sd[/code]"));
   	}
   
   
}
